import execjs
import requests

class SixHouse:
    def __init__(self):
        self.url = "https://66miniapp-api.66zhizu.com/client/search/house"
        self.headers = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Authorization": "",
            "Connection": "keep-alive",
            "Content-Type": "application/json",
            "Host": "66miniapp-api.66zhizu.com",
            "Referer": "https://servicewechat.com/wxa0545fcd02d93b5d/196/page-frame.html",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "cross-site",
            "Terminal": "windows",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x6309092b) XWEB/8555",
            "Version": "release",
            "xweb_xhr": "1"
        }
        self.params = {
            "sequence": "",
            "city:": "上海",
            "region:": "",
            "distance": "",
            "longitude": "",
            "latitude": "",
            "stations": "",
            "bed_count": "",
            "rent_type": "",
            "sort": "",
            "cost1": "",
            "cost2": ""
        }
        self.js = execjs.compile(open("六六找房.js", 'r', encoding="utf-8").read())

    def get_request(self):
        self.headers["Authorization"] = self.js.call("get_data")
        try:
            response = requests.get(url=self.url, headers=self.headers, params=self.params)
            response.raise_for_status()
            response.encoding = response.apparent_encoding
            if response.json()['code'] == 0:
                self.parse_data(response.json())
            else:
                print("数据返回错误!!!", response.json()['msg'])
        except Exception as e:
            print("数据获取失败！！！", e)

    def parse_data(self, data):
        self.params['sequence'] = data['result']['sequence']
        for info in data['result']['items']:
            photo = info['photo']
            title = info['title']
            sub_title = info['sub_title_1']
            price = info['price_label']
            print(photo, title, sub_title, price)

    def main(self):
        self.get_request()
        for page in (2, 6):
            self.get_request()


if __name__ == '__main__':
    sixhouse = SixHouse()
    sixhouse.main()
